package ua.races.command.implementation;

import ua.races.command.ServletCommand;
import ua.races.dao.RacesDaoImpl;
import org.apache.log4j.Logger;
import ua.races.vo.Staff;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

/**
 * This command is for staff's authorization
 */
public class StaffCheckCommand implements ServletCommand {

    private static final Logger log = Logger.getLogger(StaffCheckCommand.class.getName());

    public void execute(HttpServletRequest req, HttpServletResponse resp, ServletContext context) {

        final String email = req.getParameter("email").trim();
        final long password = req.getParameter("password").hashCode();
        final Staff staff;
        final HttpSession session;
        String redirectUrl="";
        String message="";
        log.info("Staff authentification");

        try {
            RacesDaoImpl dao = (RacesDaoImpl) context.getAttribute("DAO");
            staff = dao.findStaffByEmail(email);

            if ((staff != null) && (staff.getPassword() == password)) {
                session = req.getSession(true);
                if (staff.getJob().equals("admin")) {
                    session.setAttribute("admin", staff);
                    log.info("Administrator : " + staff.getLastName() + " " + staff.getFirstName() +
                            " just has come to his account");
                    req.getSession(true).setAttribute(SESS_AUTH, Boolean.TRUE);
                    message = "Authorized!";
                    redirectUrl = "prepareAdmin.do";
                }
                if (staff.getJob().equals("bookmaker")) {
                    session.setAttribute("bookmaker", staff);
                    log.info("Bookmaker : " + staff.getLastName() + " " + staff.getFirstName() +
                            " just has come to his account");
                    req.getSession(true).setAttribute(SESS_AUTH, Boolean.TRUE);
                    message = "Authorized!";
                    redirectUrl = "prepareBookmaker.do";
                }
            } else {
                log.info("Attempt to login with incorrect data");
                message = "Not Authorized!";
                redirectUrl = "index.jsp";
            }

            req.setAttribute("message", message);
            req.setAttribute("URL", redirectUrl);
            context.getRequestDispatcher("/redirection.jsp").forward(req, resp);

        } catch (SQLException e) {
            log.error(e);
        } catch (ServletException e) {
            log.error(e);
        } catch (IOException e) {
            log.error(e);
        }


    }
}